/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.alibaba.fastjson.JSONArray;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.PreShiftMeeting;
import com.koron.scene.domain.PreShiftMeetingTeamMember;
import com.koron.scene.service.api.PreShiftMeetingService;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "preShiftMeeting", description = "班前会接口")
@RestController
@RequestMapping("/preShiftMeeting")
public class PreShiftMeetingController {

    private final static Logger logger = LoggerFactory.getLogger(PreShiftMeetingController.class);
    @Autowired
    private PreShiftMeetingService preShiftMeetingService;

    @Autowired
    private Util util;

    @ApiOperation("保存班前会接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id,新增不传，修改必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "teamName", value = "班组名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shiftForeman", value = "值班长code", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "shiftForemanName", value = "值班长name", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "meetingTime", value = "时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "explains", value = "说明" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "safetyPrecautions", value = "安全注意事项" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态，0草稿，1提交" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "teamMembers", value = "班组成员列表json格式" , dataType = "String", paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存班前会接口", businessModule = "班前会", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                     @ApiIgnore PreShiftMeeting bean, @RequestParam(required = false) String teamMembers,
                                     @RequestParam(required = false) final String keepFiles,
                                     @RequestParam(required = false) final String delFiles,
                                     @RequestParam(required = false) final MultipartFile[] files) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isEmpty(teamMembers)) {
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("班前会班组成员不能为空");
            return messageBean;
        }
        List<PreShiftMeetingTeamMember> teamMemberList = JSONArray.parseArray(teamMembers, PreShiftMeetingTeamMember.class);
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return preShiftMeetingService.save(bean, teamMemberList, keepFiles, delFiles, files, user);
    }

    @ApiOperation("删除班前会接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除班组交接",businessModule = "班前会", businessManipulation = BusinessManipulation.DELETE)

    public MessageBean<Integer> delete(@RequestParam final String id, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return preShiftMeetingService.delete(id, user);
    }


    @ApiOperation("查询班前会详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<PreShiftMeeting> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<PreShiftMeeting> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return preShiftMeetingService.queryOne(id);
    }

    @ApiOperation("班前会列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "teamName", value = "班组名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<PreShiftMeeting>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode,
                                                       @RequestParam(required = false) final String teamName,@RequestParam(required = false) final String keyword,
                                                       @RequestParam(required = false) Integer containSub,
                                                       @RequestParam Integer page,
                                                       @RequestParam Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<PreShiftMeeting>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<PreShiftMeeting>> msg = preShiftMeetingService.list(user,corpCode, teamName, start, pageSize,keyword, containSub);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }


    @ApiOperation("班前会二维码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班前会id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/preShiftMeetingToImage.htm", method = RequestMethod.POST)
    public MessageBean<?> preShiftMeetingToImage(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        return preShiftMeetingService.preShiftMeetingToImage(id);
    }

    @ApiOperation("班前会二维码签到接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班前会id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/checkIn.htm", method = RequestMethod.POST)
    public MessageBean<?> preShiftMeetingToCheckIn(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String openid, @RequestParam String id, @RequestParam MultipartFile file) {
        // TODO 微信扫码时，通过用户的openid查找用户信息
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(openid, 1).getData();
            if (null != staffBeanList && staffBeanList.size() > 0) {
                user = staffBeanList.get(0);
            }
        }
        return preShiftMeetingService.preShiftMeetingToCheckIn(user, id, file);
    }
//
//    @ApiOperation("班前会导出")
//    @ApiImplicitParam(name = "id", value = "班前会id", required = true, paramType = "query", dataType = "String")
//    @RequestMapping(value = "/exports.htm", method = {RequestMethod.GET})
//    public HttpEntity<?> exports(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
//        if (null == user) {
//            return null;
//        }
//        MessageBean<PreShiftMeeting> msg = preShiftMeetingService.queryOne(id);
//        if (null == msg.getData()) {
//            return null;
//        }
//        PreShiftMeeting preShiftMeeting = msg.getData();
//        Map<String, Object> map = new HashMap<>();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        String str = preShiftMeeting.getSafetyPrecautions();
//        // 通过String.valueOf((char)10)对excel进行文本换行操作
//        String replace = str.replace("↵", String.valueOf((char) 10));
//        preShiftMeeting.setSafetyPrecautions(replace);
//        String meetTime = simpleDateFormat.format(preShiftMeeting.getMeetingTime());
//        preShiftMeeting.setMeetTime(meetTime);
//        map.put("data", preShiftMeeting);
//        File targetFile = new File("static/excel/preShiftMeeting.xlsx");
//        try {
//            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/preShiftMeeting.xlsx");
//            FileUtils.copyInputStreamToFile(in, targetFile);
//        } catch (Exception e) {
//            logger.error(e.getMessage(),e);
//        }
//        return Excel.createFile(preShiftMeeting.getTeamName() + "班前会", targetFile, "preShiftMeeting.btl", map);
//    }


    @ApiOperation("班前会导出，带图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班前会id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/exports.htm", method = RequestMethod.GET)
    public void exports(HttpServletResponse response, @RequestParam(required = false) String id) {
        // 模板
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/preShiftMeeting.xlsx");
        XSSFWorkbook workbook = null;
        Map map = preShiftMeetingService.export(id, inputStream);
        StringBuffer teamName = new StringBuffer();
        if (null != map && !map.isEmpty()) {
            if (map.containsKey("teamName")) {
                teamName.append(map.get("teamName"));
            }
            if (map.containsKey("workbook")) {
                workbook = (XSSFWorkbook) map.get("workbook");
            }
        }
        if (null != workbook) {
            try (OutputStream os = response.getOutputStream()) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(teamName.append("班前会.xlsx").toString(), StandardCharsets.UTF_8));
                workbook.write(os);
                os.flush();
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    }


    @ApiOperation("班前会列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "teamName", value = "班组名称" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> export(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, String teamName, Integer containSub) {
        if (null == user) {
            return null;
        }
        List<PreShiftMeeting> list = preShiftMeetingService.exportList(user, corpCode, teamName, containSub);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/preShiftMeetingList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/preShiftMeetingList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("班前会列表", targetFile, "preShiftMeetingList.btl", map);
    }

    @ApiOperation("班前会补录附件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班前会id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/supplementFile.htm", method = RequestMethod.POST)
    public MessageBean<?> supplementFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String id, @RequestParam MultipartFile file) {
        return preShiftMeetingService.supplementFile(user, id, file);
    }



    @ApiOperation("班前会删除附件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班前会id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fileUrl", value = "要删除的附件", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/deleteFile.htm", method = RequestMethod.POST)
    public MessageBean<?> deleteFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String id, @RequestParam String fileUrl) {
        return preShiftMeetingService.deleteFile(user, id, fileUrl);
    }
}
